package com.shenganyuan.smac;

import android.content.Context;
import android.content.Intent;

import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.view.CropImageView;
import com.oklib.CoreApp;
import com.oklib.utils.Logger.Logger;
import com.oklib.utils.Logger.inner.LogcatTree;
import com.oklib.utils.network.http.ViseHttp;
import com.oklib.utils.network.http.interceptor.HttpLogInterceptor;
import com.oklib.utils.network.loader.LoaderManager;
import com.oklib.utils.pref.AnyPref;
import com.shenganyuan.smac.activity.ActLogin;
import com.shenganyuan.smac.activity.IndexActivity;
import com.shenganyuan.smac.common.ActivityLifecycleCallbacksImpl;
import com.shenganyuan.smac.common.Config;
import com.shenganyuan.smac.common.SmacResponseInterceptor;
import com.shenganyuan.smac.common.beans.APILoginParam;
import com.shenganyuan.smac.common.beans.ApiMainUser;
import com.shenganyuan.smac.common.beans.User;
import com.shenganyuan.smac.common.utils.GlideImageLoader;
import com.shenganyuan.smac.service.location.LocationService;
import com.shenganyuan.smac.service.location.LocationStatusManager;
import com.shenganyuan.smac.service.location.Utils;
import com.uuzuche.lib_zxing.activity.ZXingLibrary;


/**
 * Created by Damon on 2017/12/10.
 */

public class App extends CoreApp {

    private static User user;
    //首页获取的用户详细信息
    private static ApiMainUser apiMainUser;
    public static String access_token = null;
    private static App mApp;

    public static synchronized App getInstance() {
        return mApp;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        mApp = this;
        //配置扫码
        ZXingLibrary.initDisplayOpinion(this);

        //配置图片选择器
        ImagePicker imagePicker = ImagePicker.getInstance();
        imagePicker.setImageLoader(new GlideImageLoader());   //设置图片加载器
        imagePicker.setShowCamera(true);  //显示拍照按钮
        imagePicker.setCrop(false);        //允许裁剪（单选才有效）
        imagePicker.setSaveRectangle(true); //是否按矩形区域保存
        imagePicker.setSelectLimit(Config.PIC_SIZE);    //选中数量限制
        imagePicker.setStyle(CropImageView.Style.RECTANGLE);  //裁剪框的形状
        imagePicker.setFocusWidth(800);   //裁剪框的宽度。单位像素（圆形自动取宽高最小值）
        imagePicker.setFocusHeight(800);  //裁剪框的高度。单位像素（圆形自动取宽高最小值）
        imagePicker.setOutPutX(1000);//保存文件的宽度。单位像素
        imagePicker.setOutPutY(1000);//保存文件的高度。单位像素
        //配置日志
        initLog();
        //配置网络
        initNet();
        //图片显示框架
        LoaderManager.getLoader().init(this);
        registerActivityLifecycleCallbacks(new ActivityLifecycleCallbacksImpl());
    }

    private void initLog() {
        Logger.getLogConfig()
                .configAllowLog(true)//是否输出日志
                .configShowBorders(false);//是否排版显示
        Logger.plant(new LogcatTree());//添加打印日志信息到Logcat的树
    }

    /**
     * 配置网络
     */
    private void initNet() {
        ViseHttp.init(this);
        ViseHttp.CONFIG()
                .baseUrl(Config.BASE_URL)
                .setCookie(true)
                .retryCount(2)
                .interceptor(new HttpLogInterceptor().setLevel(HttpLogInterceptor.Level.BODY))
                .networkInterceptor(new SmacResponseInterceptor());

    }

    /**
     * 退出登录
     *
     * @param context
     */
    public static void loginOut(Context context) {
        initFirstLoginState();
        setAccess_token("");
        clearUserInfo();
        clearUser();
        Intent intent = new Intent(context, ActLogin.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
        context.startActivity(intent);
    }

    public static void initFirstLoginState() {
        AnyPref.getDefault().putBoolean(Config.PrefKey.KEY_APP_FIRST_START, true);
    }

    public static void setCurrentUserAndToken(User user, String token) {
        App.user = user;
        AnyPref.put(user, "user");
        setAccess_token(token);

    }

    public static void setAccess_token(String token) {
        App.access_token = token;
        AnyPref.put(token, "access_token");
    }

    public static void saveUserLoginPara(APILoginParam apiLoginParam) {
        AnyPref.put(apiLoginParam, "APILoginParam");
    }

    public static APILoginParam getUserLoginPara() {
        return AnyPref.get(APILoginParam.class, "APILoginParam");
    }

    public static void clearAPILoginParam() {
        AnyPref.clear(APILoginParam.class, "APILoginParam");
    }

    /**
     * 获取当前用户
     */

    public static User getCurrentUser() {
        if (user == null) {
            user = AnyPref.get(User.class, "user");
            /**
             * 解析json后，依旧没有用户数据时,跳转至splash页面进行重新登陆操作
             */
            if (user == null) {
                loginOut(getAppContext());
            }
        }
        return user;
    }

    /**
     * 保存首页用户详细信息
     *
     * @param apiMainUser
     */
    public static void setApiMainUser(ApiMainUser apiMainUser) {
        if (apiMainUser == null) {
            return;
        }
        App.apiMainUser = apiMainUser;
        AnyPref.put(apiMainUser, "Main_User_Info");
    }

    /**
     * 获取首页用户详细信息
     *
     * @return
     */
    public static ApiMainUser getApiMainUser() {
        if (apiMainUser == null) {
            return AnyPref.get(ApiMainUser.class, "Main_User_Info");
        }
        return apiMainUser;
    }

    /**
     * 清理用户信息
     */
    public static void clearUserInfo() {
        AnyPref.clear(ApiMainUser.class, "Main_User_Info");
    }

    /**
     * 清理用户信息
     */
    public static void clearUser() {
        AnyPref.clear(User.class, "user");
    }

    public static String getAccessToken() {
        if (access_token == null) {
            access_token = AnyPref.get(String.class, "access_token");
            /**
             * 解析json后，依旧没有用户数据时,跳转至splash页面进行重新登陆操作
             */
            if (access_token == null) {
                loginOut(getAppContext());
            }
        }
        return access_token;
    }

    /**
     * 开始自动定位服务
     */
    public void startLocationService() {
        startService(new Intent(this, LocationService.class));
        LocationStatusManager.getInstance().resetToInit(this);
    }

    /**
     * 关闭自动定位服务
     * 先关闭守护进程，再关闭定位服务
     */
    public void stopLocationService() {
        sendBroadcast(Utils.getCloseBrodecastIntent());
    }

    public void exitApp() {
        System.exit(0);
    }

    /**
     * 重启APP
     * 遇到错误或者token失效的情况下再请求会重启app获取token，考虑到无限重启的情况，重启有次数限制
     * 超过重启次数将会跳转到登陆页面
     *
     * @see Config
     */
    public static void restartApp() {
        Context context = App.getInstance();
        int restartNum = AnyPref.getDefault().getInt(Config.PrefKey.KEY_RESTART_NUM_MOST, 0);
        if (restartNum <= Config.RESTART_NUM_MOST) {
            Intent launchIntent = new Intent(context, IndexActivity.class);
            launchIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
            context.startActivity(launchIntent);
            AnyPref.getDefault().putInt(Config.PrefKey.KEY_RESTART_NUM_MOST, restartNum + 1);
        } else {
            AnyPref.getDefault().putInt(Config.PrefKey.KEY_RESTART_NUM_MOST, 0);
            loginOut(context);
        }
    }

}
